package com.lazy.lib.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自带定时轮询的Cache抽象类
 *    负责定时运行任务, 具体的数据缓存在子类中实现
 * @author luodan
 *
 */
public abstract class ScheduledCache {
    protected static final Logger logger = LoggerFactory.getLogger(ScheduledCache.class);
    
    /** 定时任务 */
    protected ScheduledThreadPoolExecutor scheduledPool;
    
    /** 默认更新间隔 */
    protected long interval = 10; // 单位s
    
    /** cache data */
    protected abstract int cacheData();
    
    public ScheduledCache(){
        scheduledPool = (ScheduledThreadPoolExecutor) Executors
                .newScheduledThreadPool(1);
    }

    public ScheduledCache(int corePoolSize) {
        scheduledPool = (ScheduledThreadPoolExecutor) Executors
                .newScheduledThreadPool(corePoolSize);
    }

    public void setInterval(long interval){
        this.interval = interval;
    }
    
    public long getInterval(){
        return interval;
    }
        
    /** 开始运行cache */
    public void startCache() {
        // 10s运行一次的程序
        scheduledPool.scheduleAtFixedRate(new Runnable() {
            
            @Override
            public void run(){
                try {
                    cacheData();
                } catch (Exception e) {
                    logger.error("startCache:", e);
                }
            }
        }, 0, interval, TimeUnit.SECONDS);
    }
    
    /** 停止定时器 */
    public void shutdownCache() {
        scheduledPool.shutdown();
    }
}
